package com.gy.yemall.yemallproduct.service.impl;

import com.gy.yemall.yemallproduct.dao.CategoryBrandRelationDao;
import com.gy.yemall.yemallproduct.entity.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.common.utils.PageUtils;
import com.gy.common.utils.Query;

import com.gy.yemall.yemallproduct.dao.CategoryDao;
import com.gy.yemall.yemallproduct.entity.CategoryEntity;
import com.gy.yemall.yemallproduct.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    // 该baseMapper相当于CategoryDao
    @Override
    public List<CategoryEntity> listWithTree() {
        // 查出所有的类别
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 在所有的类别中筛选出一级类别
        List<CategoryEntity> categoryWithTree = categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() != null && categoryEntity.getParentCid() == 0;
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, categoryEntities));
            return categoryEntity;
        }).sorted((categoryEntity1, categoryEntity2) -> {
            // 这里排序需要进行判断不然出现空指针异常
            return (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort())
                    - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
        }).collect(Collectors.toList());

        return categoryWithTree;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 1.检查当前删除的菜单是否被其他地方引用，若有则不能删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPathById(Long catelogId) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        List<Long> list = new ArrayList<>();
        findParentCatelogId(categoryEntity.getCatId(), list);
        Collections.reverse(list);
        return list.toArray(new Long[list.size()]);
    }

    @Override
    public void updateCategoryAndC_B_Relation(CategoryEntity category) {
        baseMapper.updateById(category);
        // 更新关联的表，利用dao层进行更新方式
        categoryBrandRelationDao.updateCR_Relation(category.getCatId(),category.getName());
    }

    @Override
    public List<CategoryEntity> getOneTypeCategory() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntityList;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCategory2And3() {
        // 查出所有的一级分类
        List<CategoryEntity> oneTypeCategory = this.getOneTypeCategory();
        Map<String, List<Catelog2Vo>> parent_cid = oneTypeCategory.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // v作为二级分类
            List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            // 封装二级分类
            List<Catelog2Vo> collect = null;
            if (categoryEntityList != null) {
                collect = categoryEntityList.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 再进行封装三级分类
                    List<CategoryEntity> categoryEntityList1 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (categoryEntityList1 != null) {
                        List<Catelog2Vo.Catelog3Vo> collect1 = categoryEntityList1.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(collect1);

                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));

        return parent_cid;
    }

    private void findParentCatelogId(Long catId, List<Long> list) {
        CategoryEntity categoryEntity = this.getById(catId);
        list.add(categoryEntity.getCatId());
        if (categoryEntity.getParentCid() != 0) {
            findParentCatelogId(categoryEntity.getParentCid(), list);
        }
    }

    private List<CategoryEntity> getChildrens(CategoryEntity currentCategory, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> childrens = categoryEntities.stream().filter((categoryEntity) -> {
            // 说明categoryEntity为当前种类的子类
            return categoryEntity.getParentCid() == currentCategory.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, categoryEntities));
            return categoryEntity;
        }).sorted((categoryEntity1, categoryEntity2) -> {
            // 这里排序需要进行判断不然出现空指针异常
            return (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort())
                    - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
        }).collect(Collectors.toList());
        return childrens;
    }

}